import { showToast } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import Navbar from "@/components/Navbar";
import leaseStore from "@/stores/LeaseStore";
import { observer } from "mobx-react-lite";
import { useEffect, useRef, useState } from "react";
import { HouseConstant } from "@/constant/HouseConstant";
import { DatePicker, PickerOption, Loading } from "@nutui/nutui-react-taro";
import { CommonUtil } from "@/utils/CommonUtil";
import systemStore from "@/stores/SystemStore";
import RentBillBusiness from "@/business/RentBillBusiness";
import { RentBillEntity } from "@/entities/RentBillEntity";
import ConfirmPopup from "./ConfirmPopup";
import useHook from "./useHook";
import BillForm from "./BillForm";
import "./index.less";

const FillRentBill = () => {
  const { currentHouse, fillBillItems } = useHook();
  const { FieldToUnit } = HouseConstant;
  const { currentRentBillTenant } = leaseStore;
  const { houseName, tenantId, houseId, landlordId, leaseDate } =
    currentRentBillTenant;
  const billFormRef = useRef<{
    setFieldsValue: (values) => any;
    resetFields: () => any;
  }>();
  const [billDateVisible, setBillDateVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  // 是否是第一个月收租
  const [isFirstMonthBill, setIsFirstMonthBil] = useState(false);
  // 是否已经选择收租时间
  const [isSelectBillTime, setIsSelectBillTime] = useState(false);
  // 是否禁用BillForm的填写
  const [isDisabledBillForm, setIsDisabledBillForm] = useState(false);
  // 是否是查看账单（针对ConfirmPopup）
  const [isLookBill, setIsLookBill] = useState(false);
  const [showBillDate, setShowBillDate] = useState("X年X月");
  const [billDate, setBillDate] = useState("");
  // 当月的账单
  const [selectedMonthBill, setSelectedMonthBill] =
    useState<RentBillEntity.IRentBill>({} as RentBillEntity.IRentBill);
  // 账单表单的values
  const [billFormValues, setBillFormValues] = useState<any>({});
  // 账单的总钱数
  const [billTotalPrice, setBillTotalPrice] = useState(0);
  // 账单确认信息
  const [billConfirmMsg, setBillConfirmMsg] = useState<
    Array<{ key: string; text: string; value: string; dosage: number }>
  >([]);
  // 确认账单popup的visible
  const [billConfirmPopupVisible, setBillConfirmPopupVisible] = useState(false);
  // 确认popup弹框中的表格数据
  const [confirmTableData, setConfirmTableData] = useState([]);
  const [datePickRange] = useState(() => {
    // 开始时间（租赁时间）
    const [startYear, startMonth] =
      CommonUtil.formatUtcTime(leaseDate)?.split("-");
    // 结束时间
    const [endYear, endMonth] = CommonUtil.getPreviousMonth(
      `${new Date().getFullYear()}-${new Date().getMonth() + 1}`
    ).split("-");
    return [
      new Date(Number(startYear), Number(startMonth) - 1),
      new Date(Number(endYear), Number(endMonth) - 1),
    ];
  });

  /**
   * 账单日期选择
   * @param selectedOptions
   * @param selectedValue
   */
  const onBillDateConfirm = async (
    selectedOptions: PickerOption[],
    selectedValue: (string | number)[]
  ) => {
    const selectYearMonthText = selectedOptions.map((i) => i.text).join("");
    const [selectYear, selectMonth] = selectedValue;
    const [leaseYear, leaseMonth] = leaseDate?.split("-");
    const tmpBillDate = selectedValue.join("-");
    setShowBillDate(selectYearMonthText);
    setBillDate(tmpBillDate);
    billFormRef.current?.resetFields();
    // 1. 发送请求查看选中的月份是否已经收租
    const selectedMonthBill: any = await RentBillBusiness.getRentBillByBillDate(
      {
        houseId,
        landlordId,
        tenantId,
        billDate: tmpBillDate,
      }
    );
    // 该租客已经收租
    if (selectedMonthBill?.id) {
      setSelectedMonthBill(selectedMonthBill);
    }
    // 2. 该租客未收租
    else {
      setIsDisabledBillForm(false);
      // 2.1 说明该租客在当前房东的当前房子是第一个月交租
      if (selectYear == leaseYear && selectMonth === leaseMonth) {
        setIsFirstMonthBil(true);
        showToast({
          icon: "none",
          title: `该租客在${selectYearMonthText}入住，填写入住时各表的记录值`,
        });
      }
      // 2.2 说明不是第一次收租
      else {
        setIsFirstMonthBil(false);
        setIsLoading(true);
        // 发送请求获取上个月的水、电、燃气表的记录值
        const previousMonth = CommonUtil.getPreviousMonth(tmpBillDate);
        const lastRentBill: any = await RentBillBusiness.getRentBillByBillDate({
          houseId,
          landlordId,
          tenantId,
          billDate: previousMonth,
        });
        setIsLoading(false);
        // 说明上个月的租金还没有收，先让房租收取上个月的租金
        if (!lastRentBill?.id) {
          const [year, month] = previousMonth.split("-");
          showToast({
            icon: "none",
            title: `${year}年${month}月的租金还没有收取，快去收取吧`,
          });
          return;
        } else {
          billFormRef.current?.setFieldsValue({
            lastElectricityMeter: lastRentBill.lastElectricityMeter,
            lastWaterMeter: lastRentBill.lastWaterMeter,
            lastFuelMeter: lastRentBill.lastFuelMeter,
          });
        }
      }
    }
    setIsSelectBillTime(true);
  };

  useEffect(() => {
    if (selectedMonthBill?.id) {
      setIsDisabledBillForm(true);
      billFormRef.current?.setFieldsValue(selectedMonthBill);
    }
  }, [selectedMonthBill]);

  /**
   * 确定收租按钮
   * @param values
   */
  const finishFillBill = async (values) => {
    const cloneValues = {} as any;
    Reflect.ownKeys(values).forEach((key) => {
      cloneValues[key] = Number(values[key]);
    });
    const {
      lastElectricityMeter,
      electricityMeter,
      lastWaterMeter,
      waterMeter,
      lastFuelMeter,
      fuelMeter,
    } = cloneValues;
    // 验证是否已选择要收租的时间
    if (!billDate) {
      showToast({ title: "请点击X年X月来选择你要收租的月份", icon: "none" });
    }
    if (lastElectricityMeter > electricityMeter) {
      showToast({
        icon: "none",
        title: "当月的电表数值需大于或等于上个月的电表数值",
      });
    }
    if (lastWaterMeter > waterMeter) {
      showToast({
        icon: "none",
        title: "当月的水表数值需大于或等于上个月的水表数值",
      });
    }
    if (lastFuelMeter && fuelMeter && lastFuelMeter > fuelMeter) {
      showToast({
        icon: "none",
        title: "当月的燃气表数值需大于或等于上个月的燃气表数值",
      });
    }
    setBillFormValues(values);
    // 设置popup的确认信息
    setBillConfirmMsg(() => {
      const electricity = electricityMeter - lastElectricityMeter;
      const water = waterMeter - lastWaterMeter;
      let fuel;
      const arr = [
        {
          key: "electricity",
          text: "电用量：",
          value: `${electricityMeter}度 - ${lastElectricityMeter}度 = ${electricity}度`,
          dosage: electricity,
        },
        {
          key: "water",
          text: "水用量：",
          value: `${waterMeter}吨 - ${lastWaterMeter}吨 = ${water}吨`,
          dosage: water,
        },
      ];
      if (fuelMeter && lastFuelMeter) {
        fuel = fuelMeter - lastFuelMeter;
        arr.push({
          key: "fuel",
          text: "燃气用量：",
          value: `${fuelMeter}m³ - ${lastFuelMeter}m³ = ${fuel}m³`,
          dosage: fuel,
        });
      }
      arr.push({
        key: "price",
        text: "租金：",
        value: "1个月",
        dosage: 1,
      });
      const fuelExpress =
        fuelMeter && lastFuelMeter
          ? ` + ${currentHouse.fuelFee}${FieldToUnit.fuelFee} * ${fuel}m³`
          : null;

      // 总收费
      let totalFee =
        currentHouse.electricityFee * electricity +
        currentHouse.waterFee * water +
        currentHouse.price;
      if (fuelExpress) {
        totalFee += currentHouse.fuelFee * fuel;
      }
      return arr;
    });
    setBillConfirmPopupVisible(true);
  };

  useEffect(() => {
    const _confirmTableData = [] as any;
    billConfirmMsg.forEach((item) => {
      const { dosage } = item;
      switch (item.key) {
        case "electricity":
          _confirmTableData.push({
            project: "电",
            unitPrice: `${currentHouse.electricityFee}${FieldToUnit.electricityFee}`,
            dosage: dosage + "度",
            expense: currentHouse.electricityFee * dosage,
          });
          break;
        case "water":
          _confirmTableData.push({
            project: "水",
            unitPrice: `${currentHouse.waterFee}${FieldToUnit.waterFee}`,
            dosage: dosage + "吨",
            expense: currentHouse.waterFee * dosage,
          });
          break;
        case "fuel":
          _confirmTableData.push({
            project: "燃气",
            unitPrice: `${currentHouse.fuelFee}${FieldToUnit.fuelFee}`,
            dosage: dosage + "m³",
            expense: currentHouse.fuelFee * dosage,
          });
          break;
        case "price":
          _confirmTableData.push({
            project: "租金",
            unitPrice: `${currentHouse.price}元/月`,
            dosage: dosage + "月",
            expense: currentHouse.price * dosage,
          });
          break;
      }
    });
    let total = 0;
    _confirmTableData.forEach((item) => {
      total += item.expense;
    });
    _confirmTableData.push({
      project: "总费用",
      unitPrice: null,
      dosage: null,
      expense: total,
    });
    setConfirmTableData(_confirmTableData);
    setBillTotalPrice(total);
  }, [billConfirmMsg]);

  /**
   * 确认账单
   */
  const confirmBill = async () => {
    if (!isLookBill) {
      // 发送出账单的请求
      const rentBill: any = await RentBillBusiness.addRentBill({
        ...billFormValues,
        billDate,
        houseId,
        landlordId,
        tenantId,
        totalPrice: billTotalPrice,
      });
      setSelectedMonthBill(rentBill);
      showToast({ title: "收租成功", icon: "success" });
    }
    setBillConfirmPopupVisible(false);
  };

  const onLookBill = () => {
    finishFillBill(selectedMonthBill);
    setIsLookBill(true);
  };
  useEffect(() => {
    if (!billConfirmPopupVisible) {
      setIsLookBill(false);
    }
  }, [billConfirmPopupVisible]);

  return (
    <Navbar mode="back" title={houseName} bgColor="var(--mini-first)">
      <View
        className="fill-rent-bill-container"
        style={{ height: systemStore.haveNavbarNotTabbarHeight }}
      >
        <View>
          {fillBillItems.map((item) => {
            return (
              <View className="fill-bill-item">
                <Text>{item.text}</Text>
                <Text>{item.content}</Text>
              </View>
            );
          })}
        </View>
        <View className="fill-bill-wrap">
          <View className="bill-date" onClick={() => setBillDateVisible(true)}>
            <Text>我要收</Text>
            <Text>{showBillDate}</Text>
            <Text>的租</Text>
          </View>
          <BillForm
            ref={billFormRef}
            isFirstMonthBill={isFirstMonthBill}
            isSelectBillTime={isSelectBillTime}
            isDisabledForm={isDisabledBillForm}
            currentHouse={currentHouse}
            selectedMonthBill={selectedMonthBill}
            onFinish={finishFillBill}
            onLookBill={onLookBill}
          />
        </View>
        <DatePicker
          showChinese
          type="year-month"
          visible={billDateVisible}
          startDate={datePickRange[0]}
          endDate={datePickRange[1]}
          onClose={() => setBillDateVisible(false)}
          onConfirm={onBillDateConfirm}
        />
        {isLoading && (
          <View className="loading-wrap">
            <Loading>加载中</Loading>
          </View>
        )}
        <ConfirmPopup
          visible={billConfirmPopupVisible}
          tableData={confirmTableData}
          billConfirmMsg={billConfirmMsg}
          title={
            isDisabledBillForm
              ? `${showBillDate}房屋账单`
              : "请确认账单是否正确"
          }
          onClose={() => setBillConfirmPopupVisible(false)}
          onConfirm={confirmBill}
        />
      </View>
    </Navbar>
  );
};

export default observer(FillRentBill);
